package com.playball.lottery;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;
import org.json.JSONTokener;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
//modify by rain remove jPush
//import cn.jpush.android.api.InstrumentedActivity;


import com.playball.lottery.R;
import com.playball.lottery.fragment.frm.LoginFragment;
import com.playball.lottery.fragment.frm.UserCenterFragment;
import com.playball.lottery.nt.GetJsonData;
import com.playball.lottery.nt.GetRequestParams;
import com.playball.lottery.util.ConvertJsonToList;
import com.playball.lottery.util.Logger;



/**
 * @author tanglizhong
 * @version 2014-5-6 下午4:39:19
 */
//modify by rain remove jPush
public class StartupActivity extends FragmentActivity/*InstrumentedActivity*/ {
	
	private boolean isFirstIn = false;
	
	private static final int GO_HOME = 1000;
    private static final int GO_GUIDE = 1001;
    // 延迟3秒
    private static final long SPLASH_DELAY_MILLIS = 1000;
    
    private static final String SHAREDPREFERENCES_NAME = "first_pref";
    
	public static boolean isForeground = false;

	private static final String TAG = "StartupActivity";
    
    private Context mActivity;
	LoginFragment loginFragment;
	//世界杯结束标志
//    private boolean flag;
    
    public static String rb_huodong_url = "";
    public static boolean rb_huodong_isclose = true;

    /**
     * Handler:跳转到不同界面
     */
    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case GO_HOME:
				goHome();
                break;
            case GO_GUIDE:
                goGuide();
                break;
            }
            super.handleMessage(msg);
        }
    };

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.activity_startup);
		mActivity = this;
		
		ImageView iv_startup = (ImageView) findViewById(R.id.iv_startup);
		Animation animation = AnimationUtils.loadAnimation(this, R.anim.startup);
		animation.setAnimationListener(new Animation.AnimationListener() {
			
			@Override
			public void onAnimationStart(Animation animation) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onAnimationRepeat(Animation animation) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onAnimationEnd(Animation animation) {
				// TODO Auto-generated method stub
				go(SPLASH_DELAY_MILLIS);
			}
		});
		iv_startup.startAnimation(animation);
		
		ApplicationData.APPVERSION = getVerName(mActivity);
		
		init();
		
		loadHuoDong();
		
	}

	protected void goGuide() {
		Intent intent = new Intent(this, GuideActivity.class);
        startActivity(intent);
        finish();
	}

	protected void goHome() {
		Intent intent = new Intent(this, JddMainActivity.class);
        startActivity(intent);
        finish();
	}

	private void init() {
        // 使用SharedPreferences来记录程序的使用次数
        SharedPreferences preferences = getSharedPreferences(SHAREDPREFERENCES_NAME, MODE_PRIVATE);

        // 取得相应的值，如果没有该值，说明还未写入，用true作为默认值
        isFirstIn = preferences.getBoolean("isFirstIn", true);

	}
	
	private void go(long delayMillis) {
		// 使用Handler的postDelayed方法，delayMillis后执行跳转到MainActivity
		if (!isFirstIn) {
            mHandler.sendEmptyMessageDelayed(GO_HOME, delayMillis);
        } else {
            mHandler.sendEmptyMessageDelayed(GO_GUIDE, delayMillis);
        }
	}
	
	@Override
	protected void onResume() {
		isForeground = true;
		super.onResume();
		
	}


	@Override
	protected void onPause() {
		isForeground = false;
		super.onPause();
		
	}


	@Override
	protected void onDestroy() {
		super.onDestroy();
	}
	
	private static String packgeName = null;
	// 获取Name
	public static String getVerName(Context context) {
		String verName = "";
		try {
			if(packgeName == null)
				packgeName = context.getPackageName();
			verName = context.getPackageManager().getPackageInfo(packgeName, 0).versionName;
		} catch (NameNotFoundException e) {
			Log.e(TAG, e.getMessage());
		}
		return verName;
	}
	
	/**
	 * 活动加载
	 */
	private void loadHuoDong() {
		HuoDongLoader loader = new HuoDongLoader();
		String[] dyn = new String[2];
		JSONObject params1 = new JSONObject();
		dyn[0] = params1.toString();
		dyn[1] = "218";
		loader.execute(dyn);
	}
	
	/**
	 * 活动异步加载
	 */
	private class HuoDongLoader extends AsyncTask<String, Integer, String> {

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			rb_huodong_url = "";
			rb_huodong_isclose = true;
		}

		@Override
		protected String doInBackground(String... params) {
			// TODO Auto-generated method stub
			String strResult;
			String action = params[1];
			strResult = GetRequestParams.getRequestResult(params[0], action, StartupActivity.this);
			return strResult;
		}

		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
				try {
					if(result != null) {
						Logger.e(TAG, result);
						JSONTokener jsonParser = new JSONTokener(result);
						JSONObject js;
						js = (JSONObject) jsonParser.nextValue();
						if (js.getInt("Code") == 0) {
							Map<String, Object> map = new HashMap<String, Object>();
							map = ConvertJsonToList.getMap(js.getString("Data"));
							
							rb_huodong_url = map.get("wapurl").toString();
							rb_huodong_isclose = "true".equals(map.get("isclose").toString());
							
						}
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
		}
		
	}
	
	
}
